/**
 * 商品js
 */
// 加入在最前面，遇到带#号的url，刷新后会造成路由返回出现问题，所以直接跳转
var url = self.location.href.split("#");
if (url.length > 1) {
	self.location.href = url[0];
}
var v_order = new Vue({
	el: '#orderPage',
	data: {
		title: '确认下单',
		needBack: true,
		show:false,
		needReceiver: false,
		receiver: {},
		order: {
			goodses: [],
			orderFee: 0,
			goodsFee: 0,
			shoppingFee:0,
			remark: ''
		},
		payTypes:[{
			name: '微信支付',
			type: 'WEIXIN',
			icon: ['icon-weixin', 'button-success'],
			checked: true
		}, {
			name: '支付宝',
			type: 'ZHIFUBAO',
			icon: ['icon-zhifubao', 'button-default'],
			checked: false
		}, {
			name: '银联支付',
			type: 'YINLIAN',
			icon: ['icon-ai-pay-copy', 'button-warning'],
			checked: false
		}]
	},
	methods: {
		initOrder: function(cart) {
			this.order = cart;
			axios.post('/order/calculate/shipping/fee', {
				goodsFee: this.order.goodsFee
			})
			.then(function(resp) {
				if (resp.data.success) {
					v_order.order.shoppingFee = resp.data.message;
					v_order.order.shoppingFee_fmt = '￥' + (Number(resp.data.message) / 100).toFixed(2);
					v_order.order.orderFee += v_order.order.shoppingFee / 100;
					v_order.order.orderFee_fmt ='￥' +  (v_order.order.orderFee).toFixed(2);
					v_order.$foreceUpdate();
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
			axios.post('/order/reveiver/current/list', {
				filter_EQ_isDefault: true
			})
			.then(function(resp) {
				if (resp.data.success) {
					if (resp.data.rows.length == 0) {
						v_order.needReceiver = true;
					} else {
						v_order.needReceiver = false;
						v_order.receiver = resp.data.rows[0];
					}
				}
			})
			.catch(function (error) {
			    console.log(error);
			});
		},
		goback: function() {
			// 返回
		},
		gotoReceiverList: function() {
			v_receiver.show = true;
			// 返回的方法
			v_receiver.goBackPage = function(receiver) {
				v_order.receiver = receiver;
				v_order.needReceiver = false;
				v_order.$forceUpdate();
				$.router.back();
			}
			v_receiver.$nextTick(function() {
				$.router.load('#receiverPage');  //加载内联页面
				v_receiver.initReceivers(v_order.order.agentId, v_order.receiver.id);
			});
		},
		checkPayType: function(payType) {
			$.each(this.payTypes, function(i, pay) {
				pay.checked = false;
			})
			payType.checked = true;
		},
		gotoPay: function() {
			var carts = $.map(this.order.goodses, function(goods) {
				return {goodsId: goods.id, quantity: goods.selectCount};
			});
			var payType = $.map(this.payTypes, function(pt) {
				if (pt.checked) {
					return pt.type;
				}
			})[0];
			axios.post('/order/add', {
				carts: JSON.stringify(carts),
				receiverId: this.receiver.id,
				payChannel: payType,
				remark: this.order.remark
			}).then(function(resp) {
				if (resp.data.success) {
					$.modal({
						title: '操作成功',
						text: '订单已生成，暂时请尽快通过线下汇款完成支付。',
						buttons: [{
							text: '继续购物',
							onClick: function() {
								$.router.back();
								v_goods.loadGoods();
								v_goods.search = {text: ''};
								v_goods.settleAccount = {
									bg: 'bg-danger',
									pay: '请选择',
									totalAmount: '0.00',
									totalCount: 0
								};
							}
						}, {
							text: '查看我的订单',
							onClick: function() {
								self.location.href = '/center#myOrderPage';
							}
						}]
					});
				} else {
					$.toast(resp.data.message);
				}
			}).catch(function (error) {
			    console.log(error);
			});
		}
	}
});
// 商品列表的对象
var v_goods = new Vue({
	el: '#goodsPage',
	data: {
		title: '选购商品',
		needBack: false,
		navs: $.extend(true, [], navs, [{}, {active: 'active'}]),
		search: {
			text: ''
		},
		settleAccount: {
			bg: 'bg-danger',
			pay: '请选择',
			totalAmount: '0.00',
			totalCount: 0
		},
		goodses: []
	},
	methods: {
		reduceGoods: function(goods) {// 减少购买数量，每次一个
			if (goods.selectCount && goods.selectCount > 1) {
				goods.selectCount--;
			} else {
				goods.selectCount = '';
				goods.selected = false;
			}
			// 计算数量区间取出
			this.setCurrentPrice(goods);
			// 计算总价和总数量
			this.setTotalAmount();
			this.settleAccount.totalCount --;
			
			if (this.settleAccount.totalCount == 0) {
				this.settleAccount.bg = 'bg-danger';
				this.settleAccount.pay = '请选择';
			}
			this.$forceUpdate();
		},
		addGoods: function(goods) {// 增加购买数量，每次一个
			goods.selected = true;
			goods.selectCount = goods.selectCount ? (goods.selectCount + 1) : 1;
			// 计算数量区间取出
			var over = this.setCurrentPrice(goods);
			if (over) {
				$.toast('已超出每次购买的最大数量');
				goods.selectCount--;
				return false;
			}
			// 计算总价和总数量
			this.setTotalAmount();
			this.settleAccount.totalCount ++;
			
			this.settleAccount.bg = 'bg-success';
			this.settleAccount.pay = '去结算';
			this.$forceUpdate();
		},
		setCurrentPrice: function(goods) {// 设置当前价格，算是工具方法
			var overQuantity = true;
			$.each(goods.rules, function(i, rule) {
				if (rule.minQuantity<= goods.selectCount && rule.maxQuantity >= goods.selectCount) {
					goods.currentPrice = rule.price;
					goods.currentPrice_fmt = rule.price_fmt;
					overQuantity = false;
					return false;
				}
			});
			return overQuantity;
		},
		setTotalAmount: function() {// 设置总价，工具方法
			this.settleAccount.totalAmount = 0;
			$.each(this.goodses, function(i, goods) {
				if (goods.selected) {
					v_goods.settleAccount.totalAmount += goods.selectCount * goods.currentPrice / 100;
				}
			});
		},
		gotoPay: function() {
			// 选出已经购买的商品
			var cart = {
					goodses: [],
					goodsFee: v_goods.settleAccount.totalAmount,
					orderFee: v_goods.settleAccount.totalAmount,
					goodsFee_fmt: '￥' + (v_goods.settleAccount.totalAmount).toFixed(2),
					orderFee_fmt: '￥' + (v_goods.settleAccount.totalAmount).toFixed(2),
					shoppingFee_fmt: '￥0.00'
					
				};
			$.each(this.goodses, function(i, goods) {
				if (goods.selected) {
					goods.totalPrice = '￥' + (goods.selectCount * goods.currentPrice / 100).toFixed(2);
					cart.goodses.push(goods);
				}
			});
			// 传到下一步
			v_order.show = true;
			v_order.initOrder(cart);
			v_order.$nextTick(function() {
				$.router.load("#orderPage");
			});
		},
		searchGoods: function() {
			if (this.search.text) {
				this.loadGoods();
			}
		},
		clearSearchText: function() {
			this.search.text = '';
			this.loadGoods();
			this.$forceUpdate();
		},
		loadGoods: function(pageNo) {// 加载商品信息
			// 因为数量少，不考虑分页
			axios.post('/goods/my/list', {page_pageNo: pageNo ? pageNo : 1, filter_LIKE_name: this.search.text})
				.then(function(resp) {
					if (resp.data.success) {
						v_goods.goodses = resp.data.rows;
					}
				})
				.catch(function (error) {
				    console.log(error);
				});
		}
	},
	created: function() {
		this.loadGoods(1);
	}
});